import React, { Component } from 'react'
// npm i -S memoize-one
import memoizeOne from 'memoize-one'

class App extends Component {
  state = {
    n1: 1,
    n2: 2
  }
  // sum = (n1, n2) => {
  //   console.log('sum')
  //   return n1 + n2
  // }
  // memizeOne它可以把回调函数中的结果缓存，如果依赖项没有发生改变，再下一次调用时不会重新计算
  sum = memoizeOne((n1, n2) => {
    console.log('sum')
    return n1 + n2
  })
  render() {
    const { n1, n2 } = this.state
    return (
      <div>
        <input
          type="number"
          value={n1}
          onChange={(e) =>
            this.setState((state) => ({
              n1: state.n1 + Number(e.target.value)
            }))
          }
        />
        <hr />
        <div>{this.sum(n1, n2)}</div>
        <div>{this.sum(n1, n2)}</div>
        <div>{this.sum(n1, n2)}</div>
      </div>
    )
  }
}

export default App
